import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controllers/keyboard_controller.dart';

void main() {
  // 在应用启动前注册 KeyboardController
  Get.put(KeyboardController());
  runApp(const MyApp());
}

// 定义主题数据
class KeyboardTheme {
  final String name;
  final Color primaryColor;
  final Color backgroundColor;
  final Color keyBgColor;
  final Color textColor;

  const KeyboardTheme({
    required this.name,
    required this.primaryColor,
    required this.backgroundColor,
    required this.keyBgColor,
    required this.textColor,
  });
}

// 预定义的主题列表
const List<KeyboardTheme> themes = [
  KeyboardTheme(
    name: 'Green Matrix',
    primaryColor: Colors.green,
    backgroundColor: Colors.black,
    keyBgColor: Color(0xFF1A1A1A),
    textColor: Colors.green,
  ),
  KeyboardTheme(
    name: 'Deep Purple',
    primaryColor: Colors.deepPurple,
    backgroundColor: Color(0xFF1A1A1A),
    keyBgColor: Color(0xFF2D2D2D),
    textColor: Colors.deepPurple,
  ),
  KeyboardTheme(
    name: 'Ocean Blue',
    primaryColor: Colors.blue,
    backgroundColor: Color(0xFF0A192F),
    keyBgColor: Color(0xFF172A45),
    textColor: Colors.lightBlue,
  ),
  KeyboardTheme(
    name: 'Amber Glow',
    primaryColor: Colors.amber,
    backgroundColor: Color(0xFF2C2C2C),
    keyBgColor: Color(0xFF3D3D3D),
    textColor: Colors.amber,
  ),
  KeyboardTheme(
    name: 'Rose Gold',
    primaryColor: Color(0xFFFF7D7D),
    backgroundColor: Color(0xFF2D2D2D),
    keyBgColor: Color(0xFF3D3D3D),
    textColor: Color(0xFFFF7D7D),
  ),
];

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Keyboard Monitor',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final KeyboardController controller = Get.find();
  final GlobalKey _textKey = GlobalKey();
  final FocusNode _focusNode = FocusNode();
  
  @override
  void initState() {
    super.initState();
    // 确保在初始化时获得焦点
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
  }
  
  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      body: RawKeyboardListener(
        focusNode: _focusNode,
        onKey: (event) {
          controller.onKeyEvent(event);
        },
        autofocus: true,
        child: GestureDetector(
          onTap: () {
            // 确保点击任何地方都能获得焦点
            _focusNode.requestFocus();
          },
          child: Obx(() {
            final currentTheme = themes[controller.currentThemeIndex.value];
            return Scaffold(
              backgroundColor: currentTheme.backgroundColor,
              appBar: AppBar(
                backgroundColor: currentTheme.backgroundColor,
                foregroundColor: currentTheme.primaryColor,
                title: Text('Keyboard Monitor', style: TextStyle(color: currentTheme.primaryColor)),
                actions: [
                  IconButton(
                    icon: Icon(Icons.refresh, color: currentTheme.primaryColor),
                    onPressed: controller.resetTypingPractice,
                    tooltip: 'Reset Text',
                  ),
                  IconButton(
                    icon: Icon(Icons.palette, color: currentTheme.primaryColor),
                    onPressed: controller.nextTheme,
                    tooltip: 'Change Theme',
                  ),
                ],
              ),
              body: Column(
                children: [
                  Expanded(
                    child: Center(
                      child: LayoutBuilder(
                        builder: (context, constraints) {
                          return Container(
                            width: constraints.maxWidth * 0.9,
                            padding: const EdgeInsets.symmetric(horizontal: 32.0, vertical: 24.0),
                            margin: const EdgeInsets.all(16.0),
                            decoration: BoxDecoration(
                              color: currentTheme.keyBgColor,
                              border: Border.all(color: currentTheme.primaryColor.withOpacity(0.3)),
                              borderRadius: BorderRadius.circular(12.0),
                              boxShadow: [
                                BoxShadow(
                                  color: currentTheme.primaryColor.withOpacity(0.1),
                                  spreadRadius: 2,
                                  blurRadius: 5,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: SingleChildScrollView(
                              child: Container(
                                key: _textKey,
                                width: double.infinity,
                                child: Obx(() {
                                  final text = controller.targetText.value;
                                  final currentIndex = controller.currentIndex.value;
                                  final typedChars = controller.typedCharacters;
                                  final errorChars = controller.errorCharacters;
                                  
                                  return Wrap(
                                    spacing: 4.0,
                                    runSpacing: 16.0,
                                    alignment: WrapAlignment.start,
                                    children: _buildWords(
                                      text,
                                      currentIndex,
                                      typedChars,
                                      errorChars,
                                      currentTheme,
                                    ),
                                  );
                                }),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                  // 键盘布局
                  Expanded(
                    child: Container(
                      color: currentTheme.backgroundColor,
                      child: Center(
                        child: KeyboardLayout(
                          keyStates: controller.keyStates,
                          theme: currentTheme,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          }),
        ),
      ),
    );
  }

  // 构建单词列表
  List<Widget> _buildWords(String text, int currentIndex, RxList<bool> typedChars, RxList<bool> errorChars, KeyboardTheme theme) {
    List<Widget> words = [];
    List<String> characters = text.split('');
    int startIndex = 0;
    
    for (int i = 0; i <= characters.length; i++) {
      if (i == characters.length || characters[i] == ' ') {
        if (i > startIndex) {
          // 检查当前单词是否包含当前输入位置
          bool isCurrentWord = currentIndex >= startIndex && currentIndex < i;
          
          // 构建单词容器
          Widget wordWidget = Container(
            margin: const EdgeInsets.symmetric(horizontal: 4.0),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: List.generate(
                    i - startIndex,
                    (index) => Container(
                      width: 24,
                      child: _buildThemedCharacter(
                        characters[startIndex + index],
                        startIndex + index == currentIndex,
                        startIndex + index < typedChars.length && typedChars[startIndex + index],
                        startIndex + index < errorChars.length && errorChars[startIndex + index],
                        theme,
                      ),
                    ),
                  ),
                ),
                if (isCurrentWord && controller.currentTranslation.value.isNotEmpty)
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 56, // 调整这个值来控制提示框与单词的距离
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.black87,
                        borderRadius: BorderRadius.circular(4),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black26,
                            blurRadius: 4,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Text(
                        controller.currentTranslation.value,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
              ],
            ),
          );
          
          words.add(wordWidget);
        }
        
        // 添加空格
        if (i < characters.length) {
          words.add(
            Container(
              width: 24,
              margin: const EdgeInsets.symmetric(horizontal: 4.0),
              child: _buildThemedCharacter(
                ' ',
                i == currentIndex,
                i < typedChars.length && typedChars[i],
                i < errorChars.length && errorChars[i],
                theme,
              ),
            ),
          );
        }
        startIndex = i + 1;
      }
    }
    return words;
  }

  // 构建主题化的字符
  Widget _buildThemedCharacter(String char, bool isCurrent, bool isTyped, bool isError, KeyboardTheme theme) {
    final color = isError
        ? Colors.red
        : isTyped
            ? theme.primaryColor
            : theme.textColor.withOpacity(0.5);

    if (char == ' ') {
      return Container(
        height: 48,
        alignment: Alignment.center,
        child: Stack(
          children: [
            Center(
              child: Icon(
                Icons.space_bar,
                color: isTyped ? theme.primaryColor : theme.textColor.withOpacity(0.5),
                size: 24,
              ),
            ),
            if (isCurrent)
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Icon(
                  Icons.space_bar,
                  color: theme.primaryColor,
                  size: 16,
                ),
            ),
          ],
        ),
      );
    }

    return Container(
      height: 48,
      alignment: Alignment.center,
      child: Stack(
        children: [
          Center(
            child: Text(
              char,
              style: TextStyle(
                color: color,
                fontSize: 24,
                height: 1,
              ),
            ),
          ),
          if (isCurrent)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Icon(
                Icons.space_bar,
                color: theme.primaryColor,
                size: 16,
              ),
            ),
        ],
      ),
    );
  }
}

class KeyboardLayout extends StatefulWidget {
  final RxMap<String, bool> keyStates;
  final KeyboardTheme theme;

  const KeyboardLayout({
    super.key,
    required this.keyStates,
    required this.theme,
  });

  @override
  State<KeyboardLayout> createState() => _KeyboardLayoutState();
}

class _KeyboardLayoutState extends State<KeyboardLayout> {
  final KeyboardController controller = Get.find<KeyboardController>();

  // 基础按键单位宽度
  static const double _baseWidth = 50.0;
  static const double _baseHeight = 50.0;
  static const double _spacing = 4.0;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final currentTheme = themes[controller.currentThemeIndex.value];
      
      return Scaffold(
        backgroundColor: currentTheme.backgroundColor,
        body: Center(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: currentTheme.keyBgColor.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: currentTheme.primaryColor.withOpacity(0.5)),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildFunctionKeys(),
                          ),
                          const SizedBox(height: _spacing * 4),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildNumberRow(),
                          ),
                          const SizedBox(height: _spacing),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildQwertyRow(),
                          ),
                          const SizedBox(height: _spacing),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildAsdfRow(),
                          ),
                          const SizedBox(height: _spacing),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildZxcvRow(),
                          ),
                          const SizedBox(height: _spacing),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: _buildBottomRow(),
                          ),
                        ],
                      ),
                      const SizedBox(width: _spacing * 4),
                      Column(
                        children: _buildNumPad(),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget _buildKey(String label, {double widthUnit = 1, double heightUnit = 1}) {
    return Obx(() {
      final currentTheme = themes[controller.currentThemeIndex.value];
      final bool isPressed = controller.keyStates[label] ?? false;
      
      return Container(
        width: _baseWidth * widthUnit,
        height: _baseHeight * heightUnit,
        margin: const EdgeInsets.all(_spacing / 2),
        decoration: BoxDecoration(
          color: isPressed 
            ? currentTheme.primaryColor.withOpacity(0.3)
            : currentTheme.keyBgColor,
          border: Border.all(
            color: isPressed 
              ? currentTheme.primaryColor.withOpacity(0.8)
              : currentTheme.primaryColor.withOpacity(0.5),
            width: isPressed ? 2 : 1,
          ),
          borderRadius: BorderRadius.circular(5),
          boxShadow: isPressed ? [
            BoxShadow(
              color: currentTheme.primaryColor.withOpacity(0.5),
              blurRadius: 10,
              spreadRadius: 2,
            )
          ] : null,
        ),
        child: Center(
          child: Text(
            label,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: isPressed 
                ? currentTheme.primaryColor
                : currentTheme.textColor.withOpacity(0.8),
              fontSize: 14,
              fontWeight: isPressed ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      );
    });
  }

  Widget _buildSpacer([double width = _spacing * 4]) {
    return SizedBox(width: width);
  }

  List<Widget> _buildFunctionKeys() {
    return [
      _buildKey('ESC'),
      _buildSpacer(_spacing * 8),
      _buildKey('F1'),
      _buildKey('F2'),
      _buildKey('F3'),
      _buildKey('F4'),
      _buildSpacer(_spacing * 8),
      _buildKey('F5'),
      _buildKey('F6'),
      _buildKey('F7'),
      _buildKey('F8'),
      _buildSpacer(_spacing * 10),
      _buildKey('F9'),
      _buildKey('F10'),
      _buildKey('F11'),
      _buildKey('F12'),
      _buildSpacer(_spacing * 4),
      _buildKey('PRT\nSC'),
      _buildKey('SCR\nLK'),
      _buildKey('PAUSE'),
    ];
  }

  List<Widget> _buildNumberRow() {
    return [
      _buildKey('`'),
      _buildKey('1'),
      _buildKey('2'),
      _buildKey('3'),
      _buildKey('4'),
      _buildKey('5'),
      _buildKey('6'),
      _buildKey('7'),
      _buildKey('8'),
      _buildKey('9'),
      _buildKey('0'),
      _buildKey('-'),
      _buildKey('='),
      _buildKey('←', widthUnit: 2),
      _buildSpacer(),
      _buildKey('INS'),
      _buildKey('HOME'),
      _buildKey('PGUP'),
    ];
  }

  List<Widget> _buildQwertyRow() {
    return [
      _buildKey('TAB', widthUnit: 1.5),
      _buildKey('Q'),
      _buildKey('W'),
      _buildKey('E'),
      _buildKey('R'),
      _buildKey('T'),
      _buildKey('Y'),
      _buildKey('U'),
      _buildKey('I'),
      _buildKey('O'),
      _buildKey('P'),
      _buildKey('['),
      _buildKey(']'),
      _buildKey('\\', widthUnit: 1.5),
      _buildSpacer(),
      _buildKey('DEL'),
      _buildKey('END'),
      _buildKey('PGDN'),
    ];
  }

  List<Widget> _buildAsdfRow() {
    return [
      _buildKey('CAPS', widthUnit: 1.90),
      _buildKey('A'),
      _buildKey('S'),
      _buildKey('D'),
      _buildKey('F'),
      _buildKey('G'),
      _buildKey('H'),
      _buildKey('J'),
      _buildKey('K'),
      _buildKey('L'),
      _buildKey(';'),
      _buildKey('\''),
      _buildKey('ENTER', widthUnit: 2.2),
      _buildSpacer(),
    ];
  }

  List<Widget> _buildZxcvRow() {
    return [
      _buildKey('SHIFT', widthUnit: 3.0),
      _buildKey('Z'),
      _buildKey('X'),
      _buildKey('C'),
      _buildKey('V'),
      _buildKey('B'),
      _buildKey('N'),
      _buildKey('M'),
      _buildKey(','),
      _buildKey('.'),
      _buildKey('/'),
      _buildKey('SHIFT', widthUnit: 2.2),
      _buildSpacer(_spacing * 16),
      _buildKey('↑'),
    ];
  }

  List<Widget> _buildBottomRow() {
    return [
      _buildKey('CTRL', widthUnit: 1.5),
      _buildKey('WIN', widthUnit: 1.5),
      _buildKey('ALT', widthUnit: 1.5),
      _buildKey('', widthUnit: 6.5), // Space bar
      _buildKey('ALT', widthUnit: 1.5),
      _buildKey('FN', widthUnit: 1.5),
      _buildKey('CTRL', widthUnit: 1.5),
      _buildSpacer(),
      _buildKey('←'),
      _buildKey('↓'),
      _buildKey('→'),
    ];
  }

  List<Widget> _buildNumPad() {
    return [
      Row(
        children: [
          _buildKey('NUM'),
          _buildKey('/'),
          _buildKey('*'),
          _buildKey('-'),
        ],
      ),
      const SizedBox(height: _spacing * 4),
      Row(children: [
        Column(
          children: [
            Row(children: [
              _buildKey('7'),
              _buildKey('8'),
              _buildKey('9'),
            ],),
            const SizedBox(height: _spacing * 4),
            Row(children: [
              _buildKey('4'),
              _buildKey('5'),
              _buildKey('6'),
            ],),
          ],
        ),
        _buildKey('+', heightUnit: 2.5),
      ],),
      const SizedBox(height: _spacing * 4),
      Row(children: [
        Column(
          children: [
            Row(children: [
              _buildKey('1'),
              _buildKey('2'),
              _buildKey('3'),
            ],),
            const SizedBox(height: _spacing * 4),
            Row(children: [
              _buildKey('0', widthUnit: 2),
              _buildKey('.', widthUnit: 1),
            ],)
          ],
        ),
        _buildKey('ENTER', heightUnit: 2.5),
      ],),
    ];
  }
}
